import axios from 'axios'
import { Message, MessageBox } from 'element-ui'
import store from '../store'
import { getToken } from '@/utils/auth'

// 创建axios实例
const service = axios.create({
  baseURL: process.env.BASE_API, // api的base_url
  timeout: 200000, // 请求超时时间
  withCredentials: true // 选项表明了是否是跨域请求
})

// request拦截器
service.interceptors.request.use(config => {
  if (store.getters.token) {
    config.headers['X-Token'] = getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
  }
  return config
}, error => {
  // Do something with request error
  // console.log("request error ="+error) // for debug
  Promise.reject(error)
})

// respone拦截器
service.interceptors.response.use(
  response => {
    /**
    * code为非20000是抛错 可结合自己业务进行修改
    */
    const res = response.data
    if (res.code !== '000000' && res.code !== 'SYA0101') {
      Message({
        message: res.msg,
        // message:"系统繁忙，请稍后重试",
        type: 'error',
        duration: 5 * 1000
      })
      return Promise.reject('error')
    } else {
      return response.data
    }
  },
  error => {
    if (error.response) {
      const code = error.response.data.code
      if (error.response.data && error.response.data.msg) {
        error.message = error.response.data.msg
      }
      // isLogOut(error)
      Message({
        message: error.message,
        type: 'error',
        duration: 5 * 1000
      })
      // 400482:会员已退出 400470:非法的token; 400475:用户没有权限;
      // 400469:Token 过期了;
      if (code === '400470' || code === '400469' || code === '400482') {
        store.dispatch('FedLogOut').then(() => {
          location.reload()// 为了重新实例化vue-router对象 避免bug
        })
      }
    }
    return Promise.reject(error)
  }
)

export default service
